package me.firstapp.weixin.controller.member;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.ApiResult;
import com.foxinmy.weixin4j.model.Button;
import com.foxinmy.weixin4j.mp.WeixinProxy;
import com.foxinmy.weixin4j.mp.api.MenuApi;
import com.foxinmy.weixin4j.type.ButtonType;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.weixin.jinbi.JinBiAccount;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.module.weixin.order.ProductOrder;
import me.firstapp.module.weixin.weibi.WeiBiAccount;
import me.firstapp.service.weixin.account.JinBiAccountService;
import me.firstapp.service.weixin.account.WeiBiAccountService;
import me.firstapp.service.weixin.member.MemberService;
import me.firstapp.service.weixin.product.ProductOrderService;
import me.firstapp.weixin.controller.base.BaseController;

@Controller
public class MemberController extends BaseController {

	@Autowired
	private MemberService memberService;

	@Autowired
	private WeiBiAccountService weiBiAccountService;

	@Autowired
	private JinBiAccountService jinBiAccountService;

	@Autowired
	private ProductOrderService productOrderService;

	@Autowired
	private WeixinProxy weixinProxy;

	@RequestMapping("/page/memberCenterPage.htm")
	public ModelAndView memberCenter(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String openId = getCurrentLoginOpenId(request, response);
		Member member = memberService.findMemberByOpenId(openId);
		if (null == member) {
			throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
		}
		WeiBiAccount weiBiAccount = weiBiAccountService.findWeiBiAccountByCardNoAndOpenId(member.getCardNo(), openId);
		JinBiAccount jinBiAccount = jinBiAccountService.findJinBiAccountByCardNoAndOpenId(member.getCardNo(), openId);

		modelMap.put("member", member);
		modelMap.put("weiBiBalance", weiBiAccount.getBalance());
		modelMap.put("jinBiBalance", jinBiAccount.getBalance());
		return new ModelAndView("member/memberCenter", modelMap);
	}

	@RequestMapping("/page/memberFansPage.htm")
	public ModelAndView showMemberFans(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String openId = super.getCurrentLoginOpenId(request, response);
		Long fans = memberService.findTotalFansCounts(openId);
		modelMap.put("fans", fans);
		return new ModelAndView("member/fans", modelMap);
	}

	@RequestMapping("/page/getFansData.do")
	public void getFansData(@RequestParam(defaultValue = "1") int pageIndex,
			@RequestParam(defaultValue = "20") int pageSize, HttpServletRequest request, HttpServletResponse response) {
		ListObject<Member> result = new ListObject<Member>();
		try {
			String openId = super.getCurrentLoginOpenId(request, response);
			List<Member> members = memberService.findFansPage(pageIndex, pageSize, openId);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setItems(members);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping("/page/memberRankPage.htm")
	public ModelAndView showRankView(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		String openId = super.getCurrentLoginOpenId(request, response);
		Member me = memberService.findMemberByOpenId(openId);
		if (null == me) {
			throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
		}
		modelMap.put("myFansCounts", me.getFansCounts());
		JinBiAccount myJinBi = jinBiAccountService.findJinBiAccountByCardNoAndOpenId(me.getCardNo(), openId);
		modelMap.put("myJinBiBalance", myJinBi.getBalance());

		boolean isInJinBi = false;
		List<JinBiAccount> rankJinBiAccounts = jinBiAccountService.findJinBiAccountsForRank(5);
		for (int i = 0; i < rankJinBiAccounts.size(); i++) {
			if (openId.equals(rankJinBiAccounts.get(i).getOpenId())) {
				isInJinBi = true;
				modelMap.put("myJinBiRank", i + 1);
			}
			JinBiAccount jinBiAccount = rankJinBiAccounts.get(i);
			Member member = memberService.findMemberByOpenId(jinBiAccount.getOpenId());
			jinBiAccount.setAvatar(member.getAvatar());
			if (StrUtils.isNotNULL(member.getName())) {
				jinBiAccount.setName(member.getName().charAt(0) + "***");
			} else {
				jinBiAccount.setName("***");
			}
			modelMap.put("rankJinBiAccount" + i, jinBiAccount);
		}
		modelMap.put("isInJinBi", isInJinBi);

		boolean isInMember = false;
		List<Member> rankMembers = memberService.findMembersForRank(5);
		for (int i = 0; i < rankMembers.size(); i++) {
			Member member = rankMembers.get(i);
			if (openId.equals(member.getOpenId())) {
				isInMember = true;
				modelMap.put("myFansRank", i + 1);
			}
			if (StrUtils.isNotNULL(member.getName())) {
				member.setName(member.getName().charAt(0) + "***");
			} else {
				member.setName("***");
			}
			modelMap.put("rankMember" + i, member);
		}
		modelMap.put("isInMember", isInMember);
		return new ModelAndView("member/rank", modelMap);
	}

	@RequestMapping("/page/memberOrdersPage.htm")
	public ModelAndView showOrdersView(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		super.getCurrentLoginOpenId(request, response);
		return new ModelAndView("member/orders", modelMap);
	}

	@RequestMapping("/page/getOrdersData.do")
	public void getOrdersData(@RequestParam(defaultValue = "1") int pageIndex,
			@RequestParam(defaultValue = "20") int pageSize, Integer sourceType, HttpServletRequest request,
			HttpServletResponse response) {
		ListObject<ProductOrder> result = new ListObject<ProductOrder>();
		try {
			if (null == sourceType) {
				sourceType = ProductOrder.STATUS_NOT_PAY;
			}
			String openId = super.getCurrentLoginOpenId(request, response);
			List<ProductOrder> orders = productOrderService.findOrdersPage(pageIndex, pageSize, openId, sourceType);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setItems(orders);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	// 测试，上线前要注掉
	@RequestMapping("/page/test.do")
	public void test(HttpServletRequest request, HttpServletResponse response) {
		System.out.println("进入/page/test.do");
		// String url = "http://testweixin.firstapp.me";
		String url = "http://weixin.firstapp.me/weixin";
		try {
			MenuApi menuApi = new MenuApi(weixinProxy.getTokenManager());
			List<Button> buttons = new ArrayList<>();

			Button slsg = new Button("申请服务");
			slsg.setType(ButtonType.view);
			slsg.setContent(url + "/page/softBuyPage.htm");
			Button lewm = new Button("领二维码");
			lewm.setType(ButtonType.click);
			lewm.setContent("123321");
			Button yhzr = new Button("用户转让");
			yhzr.setType(ButtonType.view);
			yhzr.setContent(url + "/page/transferList.htm");
			Button kfzx = new Button("客服中心");
			kfzx.setType(ButtonType.view);
			kfzx.setContent(url + "/page/kefuPage.htm");
			Button btn1 = new Button("综合服务", slsg, lewm, yhzr, kfzx);

			// ---------------------------------------------------------------------

			Button btn2 = new Button("贝币兑换");
			btn2.setType(ButtonType.view);
			btn2.setContent(url + "/page/index.htm");

			// ----------------------------------------------------------------

			Button wdzh = new Button("我的账户");
			wdzh.setType(ButtonType.view);
			wdzh.setContent(url + "/page/memberCenterPage.htm");
			Button hqbb = new Button("获取贝币");
			hqbb.setType(ButtonType.view);
			hqbb.setContent("http://mp.weixin.qq.com/s/Gkl3eoDu069HEHGWSj20uA");
			Button ddhx = new Button("系统介绍");
			ddhx.setType(ButtonType.view);
			ddhx.setContent("http://mp.weixin.qq.com/s/tr3R2C7yxHPJZNGcfwnsCw");
			Button zqgl = new Button("赚钱攻略");
			zqgl.setType(ButtonType.view);
			zqgl.setContent("http://mp.weixin.qq.com/s/EWJk2o0tqyus5ZqmJteXlg");
			Button btn3 = new Button("个人中心", wdzh, ddhx, hqbb, zqgl);

			buttons.add(btn1);
			buttons.add(btn2);
			buttons.add(btn3);
			ApiResult apiResult = menuApi.createMenu(buttons);
			System.out.println(apiResult);
		} catch (WeixinException e) {
			e.printStackTrace();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	// // 测试，上线前要注掉
	// @RequestMapping("/page/addOutProduct.do")
	// public void addOutProduct(String orderNo, HttpServletRequest request,
	// HttpServletResponse response) {
	// YouzanTradeGetResult youzanTradeGetResult =
	// YouzanUtil.getItemId(orderNo);
	// TradeOrderV2[] tradeOrderV2s =
	// youzanTradeGetResult.getTrade().getOrders();
	// for (int i = 0; i < tradeOrderV2s.length; i++) {
	// TradeOrderV2 tradeOrderV2 = tradeOrderV2s[i];
	// outProductService.executeAddOutProduct(tradeOrderV2.getItemId(),
	// tradeOrderV2.getSkuId(),
	// tradeOrderV2.getTitle(), tradeOrderV2.getSkuPropertiesName(), "#", "#",
	// BigDecimal.ZERO,
	// BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
	// BigDecimal.ZERO,
	// BigDecimal.ZERO, BigDecimal.ZERO, "");
	// System.out.println("第" + i + "个商品添加完成");
	// }
	// }
}
